<template>
  <view class="container">

    <button @click="downloadImage" type="primary">下载图片</button>
    <view v-if="downloadProgress > 0 && downloadProgress < 100" class="progress">
      下载进度：{{ downloadProgress }}%
    </view>

    <view v-if="imagePath" class="image-container">
      <text>下载完成的图片：</text>
      <image :src="imagePath" mode="widthFix" class="image" />
    </view>
    <view v-if="errorMsg" class="error">
      {{ errorMsg }}
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg",
      imagePath: "", 
      downloadProgress: 0, 
      errorMsg: ""
    };
  },
  methods: {
    downloadImage() {
      this.downloadProgress = 0;
      this.errorMsg = "";
      this.imagePath = "";
      const downloadTask = uni.downloadFile({
        url: this.imageUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            this.imagePath = res.tempFilePath; 
            console.log("图片下载完成，本地路径：", res.tempFilePath);
          } else {
            this.errorMsg = "下载失败，状态码：" + res.statusCode;
            console.error("下载失败：", res);
          }
        },
        fail: (err) => {
          this.errorMsg = "下载失败：" + err.errMsg;
          console.error("下载出错：", err);
        }
      });

      downloadTask.onProgressUpdate((progress) => {
        this.downloadProgress = progress.progress;
        console.log(`下载进度：${progress.progress}%，已下载：${progress.totalBytesWritten/1024}KB，总大小：${progress.totalBytesExpectedToWrite/1024}KB`);
      });
    }
  }
};
</script>

<style scoped>
.container {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.title {
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.progress {
  font-size: 28rpx;
  color: #409eff;
}

.image-container {
  margin-top: 20rpx;
}

.image {
  width: 100%;
  margin-top: 10rpx;
  border-radius: 8rpx;
}

</style>